﻿using Mapster;
using SqlSugar;
using Zhp.Common.Exception;
using Zhp.Common.Helper;
using Zhp.Entity.Message.Email;
using Zhp.IService.Message.Email;
using Zhp.Model.Message.Email;
using Zhp.Service.Base;
using Zhp.SqlSugar.Repository;

namespace Zhp.Service.Message.Email
{
    public class EmailAccountService : BaseService<EmailAccount>, IEmailAccountService
    {
        public EmailAccountService(IBaseRepository<EmailAccount> rep)
        {
            _rep = rep;
        }

        public async Task<List<EmailAccountModel>> Query(QueryEmailAccountParam p)
        {
            var emailList = await _rep.GetPageListAsync(new List<IConditionalModel>
            {
                
            }, p, x => x.CreateTime, OrderByType.Desc);
            
            return emailList.Adapt<List<EmailAccountModel>>();
        }

        public async Task<bool> Create(EditEmailAccountParam p)
        {
            if (await _rep.IsAnyAsync(x => x.Email == p.Email))
            {
                throw new AlertException($"邮箱账户=>{p.Email}=>已存在!");
            }
            p.Password = p.Password.ToEncryptRSAString();
            var email = p.Adapt<EmailAccount>();
            return await _rep.InsertAsync(email);
        }

        public async Task<bool> Update(EditEmailAccountParam p)
        {
            if (await _rep.CountAsync(x => x.Email == p.Email) > 1)
            {
                throw new AlertException($"邮箱账户=>{p.Email}=>已存在!");
            }
            var email = await _rep.GetByIdAsync(p.Id);
            if (email != null)
            {
                if (email.Password != p.Password) 
                {
                    p.Password = p.Password.ToEncryptRSAString();
                }
                p.Adapt(email);
                return await _rep.UpdateAsync(email);
            }
            return false;
        }

        public async Task<bool> Delete(long id)
        {
            return await _rep.DeleteByIdAsync(id);
        }

        public async Task<List<EmailAccountSelect>> QueryAccountSelect()
        {
            return await _rep.AsQueryable().Select(x => new EmailAccountSelect { Id = x.Id, Email = x.Email }).ToListAsync();
        }

        public async Task<(Stream, string, string)> ExportExcel()
        {
            var list = await _rep.GetListAsync();

            return await ExcelHelper.Export(list.Adapt<List<EmailAccountExcel>>());
        }

        public async Task<bool> ImportExcel(Stream stream)
        {
            var excelData = await ExcelHelper.Import<EmailAccountExcel>(stream);

            return await _rep.InsertRangeAsync(excelData.Adapt<List<EmailAccount>>());
        }
    }
}
